<template>
  <div class="map-container">
    <div>
      <el-button 
        type="primary" 
        :loading="loading"
        :disabled="hasSigned"
        @click="handleSign">
        {{ hasSigned ? '今日已签到' : '立即签到' }}
      </el-button>

      <el-tag type="success" v-if="distance">
        距离签到点：{{ distance }} 米
        <span v-if="isInRange">（在范围内）</span>
        <span v-else style="color:red">（超出范围）</span>
      </el-tag>
    </div>
    <div class="map-container">
      <div id="map-container" ref="mapContainer"></div>
      <div class="map-overlay">
        <el-tag :type="isInRange ? 'success' : 'danger'">
          距离签到点：{{ distance }} 米
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script setup>
import store from '@/store'
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/util/request';

// 从接口获取的配置
const signConfig = ref({
  longitude: 0,
  latitude: 0,
  range: 1000
})

const SIGN_POINT = ref([]) // 签到点坐标
const MAX_DISTANCE = ref(1000) // 签到有效范围（米）
const map = ref(null)
const distance = ref(0)
const isInRange = ref(false)

// 加载配置
const loadConfig = async () => {
  try {
    const res = await request.post("sys/config/list")
    if(res.data.code === 200){
      const data = res.data.list
      signConfig.value = {
        longitude: parseFloat(data.find(item => item.name === '签到经度')?.value || '0'),
        latitude: parseFloat(data.find(item => item.name === '签到纬度')?.value || '0'),
        range: parseInt(data.find(item => item.name === '签到范围')?.value || '1000')
      }
      
      // 更新签到点和范围
      SIGN_POINT.value = [signConfig.value.longitude, signConfig.value.latitude]
      MAX_DISTANCE.value = signConfig.value.range
      
      // 初始化地图
      initMap()
    }else{
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error('加载配置失败: ' + error.message)
  }
}

// 在initMap函数中添加
const createSignMarker = () => {
  const icon = new AMap.Icon({
    image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
    size: new AMap.Size(32, 32),
    imageOffset: new AMap.Pixel(0, 0)
  });

  return new AMap.Marker({
    position: SIGN_POINT.value,
    map: map.value,
    icon: icon,
    title: '签到点',
    offset: new AMap.Pixel(-16, -16),
    label: {
      content: '<div class="sign-label">签到点</div>',
      offset: new AMap.Pixel(20, -10)
    }
  });
}

// 初始化地图
onMounted(() => {
  loadConfig() // 先加载配置，再初始化地图
})

const initMap = () => {
  if(!SIGN_POINT.value || SIGN_POINT.value.length === 0) return
  
  map.value = new AMap.Map('map-container', {
    zoom: 16,
    center: SIGN_POINT.value
  });

  // 添加签到点标记
  createSignMarker()
  
  // 添加范围圈
  new AMap.Circle({
    center: SIGN_POINT.value,
    radius: MAX_DISTANCE.value,
    strokeColor: '#3388ff',
    strokeOpacity: 1,
    strokeWeight: 2,
    fillColor: '#80d8ff',
    fillOpacity: 0.3,
    map: map.value
  })

  // 获取用户位置
  locateUser()
}

const locateUser = () => {
  const geolocation = new AMap.Geolocation({
    enableHighAccuracy: true,
    timeout: 10000,
    showMarker: true,
    showCircle: false,
    panToLocation: true,
    zoomToAccuracy: true
  })

  map.value.addControl(geolocation)
  
  geolocation.getCurrentPosition((status, result) => {
    if (status === 'complete') {
      handlePositionSuccess(result)
    }
  })
}

const handlePositionSuccess = (position) => {
  const userPos = [position.position.lng, position.position.lat]
  
  // 添加用户位置标记
  new AMap.Marker({
    position: userPos,
    map: map.value,
    content: '<div class="user-marker">我的位置</div>'
  })
  
  // 计算距离
  calculateDistance(userPos)
  
  // 绘制连线
  drawConnectionLine(userPos)
}

const calculateDistance = (userPos) => {
  distance.value = AMap.GeometryUtil.distance(userPos, SIGN_POINT.value).toFixed(2)
  isInRange.value = distance.value <= MAX_DISTANCE.value
}

const drawConnectionLine = (userPos) => {
  new AMap.Polyline({
    path: [userPos, SIGN_POINT.value],
    strokeColor: isInRange.value ? '#3388ff' : '#ff3333',
    strokeWeight: 3,
    strokeStyle: 'dashed',
    map: map.value
  })
}

const loading = ref(false);
const hasSigned = ref(false);

const signIn = (data) => {
  return request.post('/sys/sign', data);
};

const checkSignStatus = () => {
  const currentUser = ref(store.getters.GET_USERINFO);
  return request.get('/sys/sign/status',{
    userId: currentUser.value.id});
};

// 检查签到状态
const initCheck = async () => {
  const res = await checkSignStatus();
  hasSigned.value = res.data.msg ==="yes";
};
initCheck();

// 签到操作
const handleSign = async () => {
  try {
    loading.value = true;
    // 1. 获取用户位置
    const position = await new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject);
    });
    
    const currentUser = ref(store.getters.GET_USERINFO);

    // 2. 调用签到接口
    await signIn({
      userId: currentUser.value.id,
      lng: position.coords.longitude,
      lat: position.coords.latitude,
      address: '用户当前位置'
    });
    
    // 3. 更新状态
    if (isInRange.value) {
      ElMessage.success('签到成功');
      initCheck();
    }else {
      ElMessage.error('超出签到范围');
    }
  } catch (error) {
    ElMessage.error(error.message || '签到失败');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 500px;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

#map-container {
  width: 100%;
  height: 100%;
}

.map-overlay {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 999;
}

/* 自定义标记样式 */
.custom-marker {
  position: relative;
  width: 30px;
  height: 40px;
}

.pin {
  width: 30px;
  height: 30px;
  background: #f44336;
  border-radius: 50% 50% 50% 0;
  position: absolute;
  transform: rotate(-45deg);
  left: 0;
  top: 0;
  box-shadow: 0 0 10px rgba(0,0,0,0.3);
}

.pulse {
  background: rgba(244,67,54,0.6);
  border-radius: 50%;
  height: 14px;
  width: 14px;
  position: absolute;
  left: 8px;
  top: 8px;
  transform: rotateX(55deg);
  animation: pulse 1.5s infinite;
}

.sign-text {
  position: absolute;
  top: 35px;
  left: -15px;
  white-space: nowrap;
  background: #fff;
  padding: 2px 5px;
  border-radius: 3px;
  font-size: 12px;
  box-shadow: 0 0 3px rgba(0,0,0,0.3);
}

.user-marker {
  width: 20px;
  height: 20px;
  background: #2196F3;
  border-radius: 50%;
  border: 2px solid #fff;
  box-shadow: 0 0 5px rgba(0,0,0,0.3);
}

@keyframes pulse {
  0% { transform: scale(0.1, 0.1); opacity: 0.0; }
  50% { opacity: 1.0; }
  100% { transform: scale(1.2, 1.2); opacity: 0.0; }
}
</style>